package com.weiz.apigen;

import com.github.javaparser.JavaParser;

import com.github.javaparser.ParseResult;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.body.*;
import com.github.javaparser.ast.comments.Comment;
import com.github.javaparser.ast.expr.SimpleName;

import java.io.File;
import java.io.FileNotFoundException;

public class APIDocGenerator {
    public static void main(String[] args) throws Exception {
        final String root = "E:\\projects\\study\\spring-boot-starter\\spring-boot-starter-rabbitmq\\src\\main\\java\\com\\weiz\\apigen\\";
        String classPath = "";
        classPath = root +"MyClass.java";
        parseOneFile(classPath);
        classPath = root +"EntityA.java";
        parseOneFile(classPath);
    }

    public static void parseOneFile(String classPath) {
        ParseResult<CompilationUnit> pcu = null;
        try {
            pcu = new JavaParser().parse(new File(classPath));
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        CompilationUnit cu = pcu.getResult().get();
        NodeList<TypeDeclaration<?>> types = cu.getTypes();
        for (TypeDeclaration<?> type : types) {
            System.out.println("类" + type.getName());
            NodeList<BodyDeclaration<?>> members = type.getMembers();
            members.forEach(APIDocGenerator::processNode);
            System.out.println();
        }
    }

    /**
     * 处理类型,方法,成员
     * @param node
     */
    public static void processNode(Node node) {
        if (node instanceof TypeDeclaration) {

        } else if (node instanceof MethodDeclaration) {
            String methodName = ((MethodDeclaration) node).getName().getIdentifier();
            System.out.println("---方法:" + methodName);
        } else if (node instanceof FieldDeclaration) {
            // 变量
            String propertyInfo="";
            NodeList<VariableDeclarator> variables = ((FieldDeclaration) node).getVariables();
            SimpleName fieldName = variables.get(0).getName();
            propertyInfo = "---属性:" + fieldName + ":";
            // 注释
            Comment comment = node.getComment().orElse(null);
            String con = "";
            if (comment != null) {
                String content = comment.getContent();
                con = content.replace("*", "").trim();
                propertyInfo +=con ;
            }
            System.out.println(propertyInfo);
        }
    }
}